package com.avic.modules.realtime.client;

import com.avic.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.springframework.context.annotation.Bean;

import javax.annotation.PostConstruct;
import java.net.URI;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author ayetony.miao
 * @date 2022/8/18 10:51
 **/
@Deprecated
@Slf4j
public class WebSocketClientConfig {

    private final RedisUtils redisUtils;

    public WebSocketClientConfig(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

//    @Value("${iot_ws_bus}")
    private String DATA_ALL_URL;


    @Bean
    @PostConstruct
    public WebSocketClient webServiceClient() {
        try {
            final WebSocketClientCollector[] clientCollector = {new WebSocketClientCollector(new URI(DATA_ALL_URL), redisUtils)};

            ScheduledThreadPoolExecutor service = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);
            service.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
            service.scheduleAtFixedRate(() -> {
                log.info("[ ws 采集连接后台运行: {} {}]", DATA_ALL_URL, clientCollector[0].isCONN_ST() ? "连接正常":"连接断开");
                if (clientCollector[0].isClosed()) {
                    clientCollector[0].setCONN_ST(false);
                }
                if (!clientCollector[0].isCONN_ST()) {
                    try {
                        log.error("[ ws 重连，try to reconnect: {}]", DATA_ALL_URL);
                        clientCollector[0] = new WebSocketClientCollector(new URI(DATA_ALL_URL), redisUtils);
                        clientCollector[0].connect();
                        clientCollector[0].setCONN_ST(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("[ ws 重连失败 ，{}]", e.getMessage());
                    }
                }
            }, 3200, 7200, TimeUnit.MILLISECONDS);
            return clientCollector[0];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
